<template>
    <di>
        <Header></Header>
        <div class="messages_warp">
            <div class="content_box">
                <div class="content">
                    <div class="current_page clearFix">
                        <span>当前位置：</span>
                        <div>
                            <el-breadcrumb separator-class="el-icon-arrow-right">
                                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                                <el-breadcrumb-item>消息</el-breadcrumb-item>
                            </el-breadcrumb>
                        </div>
                    </div>
                    <div class="tap_box">
                        <el-tabs v-model="activeName" @tab-click="handleTabsClick">
                            <el-tab-pane name="1">
                                <span slot="label">
                                    <el-badge :is-dot='msgUnread > 0'>通知消息</el-badge>
                                </span>
                                <div class="message_mian">
                                    <div class="message_operation clearFix">
                                        <div class="operation">
                                            <el-checkbox v-model="noticeCheckAll" @change="handleNoticeAll">全选
                                            </el-checkbox>
                                            <el-button type="text" class="operation_inner" style="margin-left: 25px;"
                                                @click="handleNoticeDelete">删除
                                            </el-button>
                                            <el-button type="text" class="operation_inner">
                                                <el-badge :value="msgUnread" :max="msgMax" type="primary">未读消息
                                                </el-badge>
                                            </el-button>
                                            <el-button type="text" class="operation_inner" @click="read">全部标记为已读
                                            </el-button>
                                        </div>
                                        <div class="search">
                                            <el-input placeholder="请输入关键词" v-model="input3" class="input-with-select">
                                                <el-button slot="append" icon="el-icon-search"
                                                    @click="handleGetMsgList(1)">搜索
                                                </el-button>
                                            </el-input>
                                        </div>
                                    </div>
                                    <div class="message_list">
                                        <div class="message_item clearFix" v-for="item in noticeList" :key="item.id">
                                            <div class="message_title">
                                                <el-checkbox name="type" v-model="item.checkend"
                                                    @change="handleNotice(item)"></el-checkbox>
                                                <i class="is_dot" v-if="item.status == 0"></i>
                                                <i class="is_dot_hide" v-if="item.status != 0"></i>
                                                <i class="el-icon-chat-round message_icon"></i>
                                                <span style="color:#409EFF;">{{item.username}}</span>
                                                <span>{{item.title}}</span>
                                                <!-- <el-button type="text" v-if="item.flag == 1" style="margin-left: 15px;"
                                                    @click="handleFollow(item)">取消关注
                                                </el-button>
                                                <el-button type="text" v-else style="margin-left: 15px;"
                                                    @click="handleFollow(item)">关注对方
                                                </el-button> -->
                                            </div>
                                            <div class="source_time">
                                                <span>来源：云空间</span>
                                                <span style="margin-left: 20px;">{{item.time}}</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </el-tab-pane>
                            <el-tab-pane name="2">
                                <span slot="label">
                                    <el-badge :is-dot='comfirmIsDot'>确认消息</el-badge>
                                </span>
                                <div class="acceptMsg">
                                    <div class="acceptMsg_list">
                                        <div class="acceptMsg_operation clearFix">
                                            <div class="msg_title">
                                                <span>验证确认</span>
                                            </div>
                                            <div class="operation">
                                                <el-checkbox v-model="taskAll" label="全选" name="type"
                                                    @change="handleTaskAll" style=" margin-right: 25px;"></el-checkbox>
                                                <el-button type="text" class="operation_inner"
                                                    @click="handleConfirmMsgDel('del')">
                                                    删除
                                                </el-button>
                                                <el-button type="primary" size="mini" class="operation_inner"
                                                    @click.native="handleBatchConfirmOrReject('1')">确认
                                                </el-button>
                                                <el-button type="danger" size="mini"
                                                    @click.native="handleBatchConfirmOrReject('2')">
                                                    拒绝
                                                </el-button>
                                            </div>
                                        </div>
                                        <div class="list" v-for="item in taskList" :key="item.id">
                                            <div class="list_title clearFix">
                                                <!-- <p><span>{{item.title}}</span><span class="time">{{item.time}}</span>
                                                </p> -->
                                            </div>
                                            <div class="list_content clearFix">
                                                <div class="check">
                                                    <!-- <el-checkbox v-model="item.checkend" :disabled="item.status !== 0" @change="handleTask(item)"> -->
                                                    <el-checkbox v-model="item.checkend" :disabled="item.status !== 0"
                                                        @change="handleTask(item)">
                                                    </el-checkbox>
                                                </div>
                                                <div class="avatar">
                                                    <el-avatar :size="60" :src="item.img" @error="errorHandler">
                                                        <img :src="item.img?baseUrl+item.img:src" />
                                                    </el-avatar>
                                                </div>
                                                <div class="dateil">
                                                    <p>账户名：{{item.username}}</p>
                                                    <p>
                                                        <span>信息:{{item.title}}</span>
                                                        <span class="guanx">时间:{{item.time}}</span>
                                                    </p>
                                                </div>
                                                <div class="list_operation">
                                                    <el-button size="mini" v-if="item.status == 0" type="primary"
                                                        class="btn" @click.native="handleConfirmOrReject(1,item.id)">确认
                                                    </el-button>
                                                    <el-button size="mini" v-if="item.status == 0" type="danger"
                                                        class="btn" @click.native="handleConfirmOrReject(2,item.id)">拒绝
                                                    </el-button>
                                                    <span class="yqued" v-if="item.status == 1">已确认</span>
                                                    <span class="yqued" v-if="item.status == 2"
                                                        style="color:#F56C6C;">已拒绝</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </el-tab-pane>
                        </el-tabs>
                    </div>
                </div>

                <div style="width: 100%;height: 52px;"></div>

                <div class="block">
                    <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        :current-page="page" :page-sizes="[10, 15, 20, 25]" :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper" :total="total">
                    </el-pagination>
                </div>

                <el-dialog :visible.sync="dialogVisible" width="400px">
                    <div class="grouping">
                        <div class="grouping_title">
                            <span>选择分组</span>
                        </div>
                        <ul class="radio_group">
                            <li>
                                <span>学校</span>
                                <el-radio v-model="radio" label="1">{{''}}</el-radio>
                            </li>
                            <li>
                                <span>老师</span>
                                <el-radio v-model="radio" label="2">{{''}}</el-radio>
                            </li>
                            <li>
                                <span>最亲</span>
                                <el-radio v-model="radio" label="3">{{''}}</el-radio>
                            </li>
                            <li>
                                <span>校友</span>
                                <el-radio v-model="radio" label="4">{{''}}</el-radio>
                            </li>
                        </ul>
                        <div class="establish">
                            <el-button type="text"><i class="el-icon-circle-plus" style="margin-right:5px;"></i>创建新分组
                            </el-button>
                        </div>
                        <el-row>
                            <el-button size="mini" @click="dialogVisible=false">暂不分组</el-button>
                            <el-button size="mini" type="primary" @click="dialogVisible=false">保存</el-button>
                        </el-row>
                    </div>
                </el-dialog>
            </div>
            <Footer></Footer>
        </div>
    </di>
</template>

<script>
    import {
        mapState
    } from "vuex";
    import {
        websocketcUrl
    } from '@/utils/common'
    import Footer from '@c/Footer/footer'
    import SpaceHeader from '@c/spaceHeader/spaceHeader'
    import axios from 'axios'
    import Header from "@c/Header/head";
    export default {
        components: {
            Footer,
            SpaceHeader,
            Header
        },
        computed: {
            ...mapState({
                user: state => state.userModule.user
            })
        },
        created() {
            // this.initWebSocket()
            // this.initWebSocket1()
            this.handleGetMsgList(1);
            this.handleGetMsgList(2);
        },
        beforeMount() {},
        destroyed() {
            this.websocketclose()
            this.websocketclose1()
        },
        data() {
            return {
                noticeIsDot: false,
                comfirmIsDot: false,
                baseUrl: 'http://topsmart.xyz:1315/', // 服务器静态资源地址
                src: require('../../../assets/img/headportrait01.jpg'),
                activeName: '1',
                input3: '',
                taskAll: false,
                noticeList: [], // 通知消息列表
                dialogVisible: false,
                radio: '',
                msgUnread: 0, // 未读消息
                msgMax: 99, // 显示未读消息最大值
                type: 1, // 个人中心标识
                noticeCheckAll: false, // 通知全选按钮
                page: 1, // 分页当前页
                pageSize: 10, // 每页显示条数
                total: 0, // 总条数
                tabIndex: 0, // tab切换标识，防止重复点击
                selectList: [], // 通知消息选择后存放
                taskList: [], // 确认消息列表
                taskSelectList: [] // 确认消息勾选存放
            }
        },
        methods: {
            // 关注||取消关注
            handleFollow(followID) {
                if (followID.flag == 0) {
                    this.$store.dispatch('studentAnsweringModule/addFollow', {
                        id: followID.issueid,
                        lenve: 1
                    }).then(res => {
                        if (res.data.code == 200) {
                            this.$message.success('关注成功')
                            this.noticeList.map(item => {
                                if (item.issueid == followID.issueid) {
                                    item.flag = 1
                                }
                            })
                        }
                    })
                } else {
                    this.$store.dispatch('studentAnsweringModule/beanremove', {
                        userId: followID.issueid
                    }).then(res => {
                        if (res.data.code == 200) {
                            this.$message.success('取消关注成功')
                            this.noticeList.map(item => {
                                if (item.issueid == followID.issueid) {
                                    item.flag = 0
                                }
                            })
                        }
                    })
                }
            },
            initWebSocket: function () {
                // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
                var webSocketUrl = 'ws://' + websocketcUrl + 'websocket/notice' + this.user.userId
                this.websock = new WebSocket(webSocketUrl);
                this.websock.onopen = this.websocketonopen;
                this.websock.onerror = this.websocketonerror;
                this.websock.onmessage = this.websocketonmessage;
                this.websock.onclose = this.websocketclose;
            },
            websocketonopen: function () {
                // console.log("notice连接成功");
            },
            websocketonerror: function (e) {
                // console.log("notice连接发生错误");
            },
            websocketonmessage: function (e) {
                // console.log(e.data)
                if (e.data == 'notice') {
                    this.handleGetMsgList(1);
                }
            },
            websocketclose: function (e) {
                // console.log("notice关闭连接");
            },
            initWebSocket1: function () {
                // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
                var webSocketUrl = 'ws://' + websocketcUrl + 'websocket/comfirm' + this.user.userId
                this.websock1 = new WebSocket(webSocketUrl);
                this.websock1.onopen = this.websocketonopen1;
                this.websock1.onerror = this.websocketonerror1;
                this.websock1.onmessage = this.websocketonmessage1;
                this.websock1.onclose = this.websocketclose1;
            },
            websocketonopen1: function () {
                // console.log("comfirm连接成功");
            },
            websocketonerror1: function (e) {
                // console.log("comfirm连接发生错误");
            },
            websocketonmessage1: function (e) {
                if (e.data == 'comfirm') {
                    this.handleGetMsgList(2)
                }
            },
            websocketclose1: function (e) {
                // console.log("comfirm关闭连接");
            },
            // 消息标已读
            read() {
                // console.log(this.selectList)
                var ids = ''
                if (this.selectList.length > 0) {
                    this.selectList.map(item => {
                        ids += "," + item.id
                    })
                    this.$store.dispatch('messageModule/read', {
                        ids: ids.slice(1),
                        status: 1,
                        userid: this.user.userId
                    }).then(res => {
                        if (res.data.code === 200) {
                            this.selectList = []
                            this.noticeCheckAll = false
                            this.handleGetMsgList(1)
                        } else {
                            this.$message({
                                message: res.data.msg,
                                type: 'warning'
                            });
                        }
                    })
                } else {
                    this.$message.warning('请先选择数据！')
                }

            },
            // 消息
            goMessage(userId) {
                this.$router.push({
                    path: "/message",
                    query: userId
                });
            },
            // tabs标签页切换
            handleTabsClick(tab, event) {
                if (tab.index != this.tabIndex) {
                    this.page = 1
                    this.pageSize = 10
                    this.total = 0
                    this.tabIndex = tab.index;
                    if (tab.index == 0) {
                        this.handleGetMsgList(1);
                    } else {
                        this.handleGetMsgList(2);
                    }
                }
            },

            // 分页每页显示条数
            handleSizeChange(val) {
                this.pageSize = val
                this.handleGetMsgList(this.activeName)
            },

            // 分页当前页
            handleCurrentChange(val) {
                this.page = val
                this.handleGetMsgList(this.activeName)
            },

            // 去往个人中心
            goPersonal() {
                let type = this.type;
                this.$router.push({
                    path: '/personal',
                    query: type
                })
            },

            // 头像加载失败
            errorHandler() {
                return true;
            },

            // 获取通知消息列表
            handleGetMsgList(params) {
                const loading = this.$loading({
                    lock: true,
                    text: '加载中...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.2)'
                });
                this.$store.dispatch('messageModule/getMsgList', {
                    page: this.page,
                    pageSize: this.pageSize,
                    userid: this.user.userId,
                    type: params,
                    query: this.input3
                }).then(res => {
                    if (res.data.code === 200) {

                        this.total = res.data.result.page.total;
                        let list = res.data.result.page.list
                        list.forEach(item => {
                            item.checkend = false
                        });
                        if (params == 1) {
                            this.msgUnread = res.data.result.unreadNum
                            this.noticeList = list;
                        } else {
                            if (res.data.result.unreadNum > 0) {
                                this.comfirmIsDot = true
                            } else {
                                this.comfirmIsDot = false
                            }
                            this.taskList = list
                        }

                    } else {
                        this.$message({
                            message: res.data.msg,
                            type: 'warning'
                        });
                    }
                    loading.close()
                }).catch(err => {
                    this.$message.error('服务器内部错误');
                    loading.close()
                })
            },

            // 通知消息复选框勾选
            handleNotice(params) {
                if (params.checkend) {
                    this.selectList.push(params)
                } else {
                    this.selectList = this.selectList.filter(item => item.id !== params.id)
                }
                if (this.selectList.length === this.noticeList.length) {
                    this.noticeCheckAll = true
                } else {
                    this.noticeCheckAll = false
                }
            },

            // 通知消息全选
            handleNoticeAll() {
                if (this.noticeCheckAll) {
                    this.selectList = this.noticeList
                    this.noticeList.forEach(item => {
                        item.checkend = true
                    })
                } else {
                    this.selectList = [];
                    this.noticeList.forEach(item => {
                        item.checkend = false
                    })
                }
            },

            // 通知消息删除
            handleNoticeDelete() {
                if (this.selectList.length <= 0) {
                    this.$message('请先选择需要删除的消息');
                } else {
                    this.$confirm('确定删除所选的' + this.selectList.length + '条消息吗？', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'info'
                    }).then(() => {
                        let deleteID = this.selectList.map(item => {
                            return item.id
                        })
                        const loading = this.$loading({
                            lock: true,
                            text: '正在删除!',
                            spinner: 'el-icon-loading',
                            background: 'rgba(0, 0, 0, 0.2)'
                        });
                        this.$store.dispatch('messageModule/handleDeleteMessage', {
                            ids: deleteID.join(','),
                            status: 'del'
                        }).then(res => {
                            if (res.data.code === 200) {
                                this.$notify({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                this.handleGetMsgList(1)
                            } else {
                                this.$notify({
                                    message: res.data.msg,
                                    type: 'warning'
                                });
                            }
                            loading.close()
                        }).catch(err => {
                            loading.close()
                            this.$notify.error({
                                message: '删除失败'
                            });
                        })
                    }).catch(() => {
                        // console.log('点击取消')
                    });
                }
            },

            // 确认消息复选框勾选
            handleTask(params) {
                if (params.checkend) {
                    this.taskSelectList.push(params)
                } else {
                    this.taskSelectList = this.selectList.filter(item => item.id !== params.id)
                }
                if (this.taskSelectList.length === this.taskList.length) {
                    this.taskAll = true
                } else {
                    this.taskAll = false
                }
            },

            // 确认消息全选
            handleTaskAll() {
                if (this.taskAll) {
                    this.taskSelectList = this.taskList
                    this.taskList.forEach(item => {
                        if (item.status == 0) {
                            item.checkend = true
                        }
                    })
                } else {
                    this.taskSelectList = [];
                    this.taskList.forEach(item => {
                        item.checkend = false
                    })
                }
            },

            // 确认消息 || 拒绝——请求
            handleConfirmOrReject(status, id) {
                const loading = this.$loading({
                    lock: true,
                    text: '请稍等...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.2)'
                });
                this.$store.dispatch('messageModule/msgConfirmOrReject', {
                    id: id,
                    status: status,
                    userid: this.user.userId
                }).then(res => {
                    if (res.data.code === 200) {
                        this.$notify({
                            message: '操作成功',
                            type: 'success'
                        });
                        this.taskSelectList = []
                        this.handleGetMsgList(2)
                    } else {
                        this.$notify({
                            message: res.data.msg,
                            type: 'warning'
                        });
                    }
                    loading.close()
                }).catch(err => {
                    loading.close()
                    // this.$notify.error({
                    //     message: '操作失败'
                    // });
                })
            },

            // 批量确认||拒绝
            handleBatchConfirmOrReject(param) {
                let result = this.taskSelectList
                if (result.length <= 0) {
                    this.$message('请先选择需要操作的消息');
                    return false
                }
                let deleteID = result.map(item => {
                    return item.id
                })

                this.handleConfirmOrReject(param, deleteID.join(','))
            },

            // 确认消息删除
            handleConfirmMsgDel(params) {
                this.taskSelectList = this.taskSelectList.filter(item => item.status == 0)
                if (this.taskSelectList.length <= 0) {
                    this.$message('请先选择需要操作的消息');
                } else {
                    this.$confirm('确定操作所选的' + this.taskSelectList.length + '条消息吗？', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'info'
                    }).then(() => {
                        var status = params ? params : 'del'
                        var ids = ''
                        this.taskSelectList.map(item => {
                            ids += "," + item.id
                        })
                        this.$store.dispatch('messageModule/updateOrDel', {
                            ids: ids,
                            status: status
                        }).then(res => {
                            if (res.data.code == 200) {
                                this.taskSelectList = []
                                this.handleGetMsgList(2)
                                this.taskAll = false
                            }
                        })
                    }).catch(() => {});
                }
            }

        },

    }
</script>

<style lang="scss" scoped>
    /deep/.el-badge__content.is-fixed {
        right: 1px;
    }

    /deep/.el-badge__content.is-dot {
        margin-top: 10px;
    }

    .messages_warp {
        width: 100%;

        .header_box {
            width: 100%;

            .header {
                box-sizing: border-box;
                padding: 15px 0;
                margin: 0 auto;
                width: 80%;

                .title {
                    font-size: 24px;
                    color: rgb(64, 158, 255);
                    text-align: left;
                }

                .collocation>div {
                    float: left;
                }

                .collocation {
                    float: right;

                    .county {
                        color: rgb(64, 158, 255);
                        margin: 10px 50px 0 0;
                    }

                    .search {
                        width: 400px;
                    }

                    .messge {
                        cursor: pointer;
                        margin: 10px 50px 0 50px;
                    }

                    .setup {
                        margin-top: 10px;
                        cursor: pointer;
                    }
                }
            }
        }

        .content_box {
            width: 100%;
            min-height: calc(100vh - 175px);

            background-color: white;
            position: relative;
            box-sizing: border-box;
            padding-top: 10px;

            .content {
                width: 80%;
                box-sizing: border-box;
                padding: 10px 0;
                margin: 0 auto;

                .tap_box {
                    margin-top: 10px;

                    .message_mian {
                        width: 100%;

                        .message_operation {
                            box-sizing: border-box;
                            padding: 10px 20px;
                            background-color: #CCEEFF;

                            .operation {
                                float: left;

                                .operation_inner {
                                    margin-right: 25px;
                                }
                            }

                            .search {
                                float: right;
                                width: 400px;
                            }
                        }

                        .message_list {
                            box-sizing: border-box;
                            padding: 5px 20px;
                            height: 535px;
                            overflow-y: auto;

                            .message_item {
                                box-sizing: border-box;
                                padding: 15px 0;
                                border-bottom: 1px solid #F5F5F5;

                                .message_title {
                                    float: left;
                                    font-size: 14px;
                                    cursor: pointer;

                                    .is_dot {
                                        display: inline-block;
                                        width: 12px;
                                        height: 12px;
                                        border-radius: 50%;
                                        background-color: #409EFF;
                                        margin-left: 30px;
                                        margin-right: 5px;
                                    }

                                    .is_dot_hide {
                                        display: none;
                                        display: inline-block;
                                        width: 12px;
                                        height: 12px;
                                        border-radius: 50%;
                                        background-color: #5f6266;
                                        margin-left: 30px;
                                        margin-right: 5px;
                                    }

                                    .message_icon {
                                        margin-right: 30px;
                                    }
                                }

                                .source_time {
                                    float: right;
                                    font-size: 14px;
                                    color: #999;
                                    margin-top: 10px;
                                }
                            }
                        }
                    }

                    .acceptMsg {
                        width: 100%;

                        .acceptMsg_operation {
                            box-sizing: border-box;
                            padding: 10px 20px;
                            background-color: #CCEEFF;

                            .msg_title {
                                float: left;
                                font-size: 16px;
                                color: #409EFF;
                                line-height: 40px;
                            }

                            .operation {
                                float: right;

                                .operation_inner {
                                    margin-right: 25px;
                                }
                            }
                        }

                        .list {
                            margin: 5px 0;
                            box-sizing: border-box;
                            padding: 10px 15px;
                            background-color: #F5F5F5;

                            .list_title {
                                text-align: left;
                                color: #606266;
                                font-size: 15px;

                                .time {
                                    float: right;
                                    color: #606266;
                                    font-size: 14px;
                                }

                                p {
                                    margin-block-start: 4px;
                                    margin-block-end: 6px;
                                }
                            }

                            .list_content {
                                .check {
                                    margin: 20px 10px 0 0;
                                }

                                .avatar,
                                .check {
                                    float: left;
                                }

                                .dateil {
                                    float: left;
                                    margin-left: 15px;

                                    p {
                                        font-size: 15px;
                                        color: #606266;
                                        text-align: left;
                                        margin-block-start: 6px;
                                        margin-block-end: 6px;

                                        .guanx {
                                            font-size: 14px;
                                            margin-left: 30px;
                                        }
                                    }
                                }

                                .list_operation {
                                    float: right;

                                    .yqued {
                                        display: inline-block;
                                        margin-top: 20px;
                                        color: #606266;
                                        font-size: 14px;
                                    }

                                    .btn {
                                        margin-top: 12px;
                                    }
                                }
                            }
                        }
                    }

                }

                .current_page {
                    text-align: left;
                    font-weight: 400;
                    color: #606266;
                    font-size: 14px;

                    span {
                        float: left;
                    }

                    &>div {
                        float: left;
                        margin-top: 3px;
                    }
                }
            }

            .block {
                box-sizing: border-box;
                padding: 10px 0;
                margin: auto;
                position: absolute;
                bottom: 0;
                left: 50%;
                transform: translateX(-50%);
            }
        }
    }

    .grouping {
        .grouping_title {
            box-sizing: border-box;
            padding: 10px;
            color: #409EFF;
            text-align: center;
            border-bottom: 1px solid #DCDFE6;
        }

        .radio_group {
            list-style-type: none;
            margin-block-start: 0;
            margin-block-end: 0;
            padding-inline-start: 2px;

            li {
                display: flex;
                justify-content: space-between;
                align-items: center;
                box-sizing: border-box;
                padding: 10px;
                border-bottom: 1px solid #DCDFE6;

            }
        }

        label>.el-radio__label {
            display: none !important;
        }
    }

    .clearFix::after {
        content: "";
        display: block;
        width: 100%;
        font-size: 0;
        clear: both;
    }
</style>